<template>
  <div>
    <van-nav-bar
      style="background-color: #087"
      title="城市列表"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-index-bar :index-list="indexList" highlight-color="#087">
      <div v-for="item in resultList" :key="item.letter">
        <van-index-anchor :index="item.letter"></van-index-anchor>
        <div class="content" v-for="row in item.list" :key="row.value">
          <van-cell :title="`${row.label}`" @click="changeCity(row.label)" />
        </div>
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import { getCity, hotCity } from '@/api/area'

export default {
  name: 'CityPage',
  data () {
    return {
      level: 1,
      indexList: [],
      // 获得的数据
      renderData: [],

      // 被分类好的数组对象
      province: {},

      // 处理后的数组
      resultList: [
        {
          letter: '热',
          list: []
        }
      ],
      cityName: JSON.parse(localStorage.getItem('cityName')) || '上海'
    }
  },
  async created () {
    const data = await getCity(this.level)

    const hot = await hotCity()

    // console.log(hot.body)

    hot.body.forEach(item => {
      this.resultList[0].list.push(item)
    })

    this.renderData = data.body

    // console.log(this.renderData)

    // 将数据提取成数组对象，给每个字母开头的城市进行不同的分类
    this.renderData.map(item => {
      const data = item.pinyin[0].toUpperCase()
      // console.log(data)
      if (this.province[data]) {
        // console.log(this.province[data])
        this.province[data].push(item)
      } else {
        this.province[data] = [item]
      }
    })
    // console.log(this.province)

    // 将数据遍历成数组
    for (const key in this.province) {
      const obj = { letter: key, list: this.province[key] }
      this.resultList.push(obj)
    }
    // console.log(this.resultList)

    this.resultList.sort((a, b) => {
      return a.letter.localeCompare(b.letter)
    })

    this.resultList.forEach(item => this.indexList.push(item.letter))
  },
  methods: {
    onClickLeft () {
      this.$router.push('/home/list')
    },
    changeCity (value) {
      console.log(value)
      // console.log(this.renderData)
      const localCity = this.renderData.find(item => {
        return item.label === value
      })
      console.log(localCity)
      this.cityName = localCity
      this.$nextTick(() => {
        this.$router.push('/home/homepage')
      })
    }
  },
  watch: {
    cityName: {
      immediate: true,
      deep: true,
      handler (newvar) {
        localStorage.setItem('cityName', JSON.stringify(newvar))
      }
    }
  }
}
</script>

<style scoped>
.van-nav-bar {
  background-color: #087;
}
::v-deep .van-index-bar__sidebar {
  margin-top: 7px;
}
::v-deep .van-index-bar__index {
  font-size: 14px;
  margin-top: 7px;
}
.content {
  font-size: 15px;
  padding: 6px 0;
  border-bottom: 1px solid #eeeeee;
}
</style>
